<template>
  <BasicDrawer
    v-bind="$attrs"
    @close="onClose"
    @register="registerDrawer"
    title="数据规则配置"
    width="740px"
    :rootClassName="selectedMenuData?.rootClassName"
  >
    <!-- 百特搭权限配置弹窗 -->
    <div class="btd-permission-dialog" v-show="selectedMenuData?.menuSourceType === 'btd'">
      <iframe id="btd-permission-iframe" :src="btdPermissionSettingUrl"></iframe>
    </div>

    <!-- 普通页面权限配置弹窗 -->
    <a-tabs v-show="selectedMenuData?.menuSourceType !== 'btd'" defaultActiveKey="1">
      <a-tab-pane tab="数据规则" key="1">
        <a-checkbox-group v-model:value="dataRuleChecked" v-if="dataRuleList.length > 0">
          <a-row>
            <a-col :span="24" v-for="(item, index) in dataRuleList" :key="'dr' + index">
              <a-checkbox :value="item.id">{{ item.ruleName }}</a-checkbox>
            </a-col>

            <a-col :span="24">
              <div style="width: 100%; margin-top: 15px">
                <a-button @click="saveDataRuleForRole" type="primary" size="small"> <Icon icon="ant-design:save-outlined" />点击保存</a-button>
              </div>
            </a-col>
          </a-row>
        </a-checkbox-group>
        <div v-else><h3>无配置信息!</h3></div>
      </a-tab-pane>
    </a-tabs>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, unref } from 'vue';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { queryDataRule, saveDataRule } from '../role.api';
  // 声明Emits
  const emit = defineEmits(['success', 'register']);
  const { createMessage } = useMessage();
  // 声明数据
  const functionId = ref('');
  const roleId = ref('');
  const dataRuleList = ref<any[]>([]);
  const dataRuleChecked = ref([]);

  const selectedMenuData = ref<any>({});
  const btdPermissionId = ref('');
  const btdPermissionSettingUrl = ref('/console-front/#/authority/permission-group-function');
  const menuData = ref({});

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    await reset();
    setDrawerProps({ confirmLoading: false });
    //权限的id
    functionId.value = data.functionId;
    //角色的id
    roleId.value = data.roleId;
    // 选中的菜单数据
    selectedMenuData.value = data.selectedData;
    menuData.value = {
      permissionId: data.btdPermissionId,
      appId: data.selectedData.menuResourceAppId,
      formKey: data.selectedData.menuResourceId,
      menuId: data.selectedData.value,
      pageType: data.selectedData.menuResourceType,
    };
    if (data.selectedData?.menuSourceType === 'btd') {
      // 百特搭轻应用权限id
      btdPermissionId.value = data.btdPermissionId;
      sendPermissionMsg();
    } else {
      //查询数据
      const res = await queryDataRule({ functionId: unref(functionId) || '', roleId: unref(roleId) || '' });
      if (res.success) {
        dataRuleList.value = res.result.datarule;
        if (res.result.drChecked) {
          dataRuleChecked.value = res.result.drChecked.split(',');
        }
      }
    }
  });

  // 监听百特搭弹窗加载完毕事件
  // 发送消息将当前选中菜单信息传递过去
  window.addEventListener('message', (event) => {
    if (event.data.type === 'OnPermissionPageLoaded') {
      sendPermissionMsg();
    }
  });

  // 向iframe传递当前菜单变更事件及数据
  const sendPermissionMsg = () => {
    // 获取百特搭权限iframe
    const btdPermissionIframe = document.getElementById('btd-permission-iframe') as HTMLIFrameElement;
    if (btdPermissionIframe) {
      const message = {
        type: 'OnMenuChange',
        data: JSON.stringify(menuData.value),
      };
      btdPermissionIframe?.contentWindow?.postMessage(message, '*');
    }
  };
  /**
   * 重置
   */
  function reset() {
    functionId.value = '';
    roleId.value = '';
    dataRuleList.value = [];
    dataRuleChecked.value = [];
  }

  /**
   * 提交
   */
  async function saveDataRuleForRole() {
    if (!unref(dataRuleChecked) || unref(dataRuleChecked).length == 0) {
      createMessage.warning('请注意，现未勾选任何数据权限!');
    }
    let params = {
      permissionId: unref(functionId),
      roleId: unref(roleId),
      dataRuleIds: unref(dataRuleChecked).join(','),
    };
    await saveDataRule(params);
    //关闭弹窗
    closeDrawer();
    //刷新列表
    emit('success');
  }

  // 关闭抽屉时通知
  function onClose() {
    // 获取百特搭权限iframe
    // 通知百特搭权限配置iframe关闭
    const btdPermissionIframe = document.getElementById('btd-permission-iframe') as HTMLIFrameElement;
    if (btdPermissionIframe) {
      const message = { type: 'OnHidePermissionPage' };
      btdPermissionIframe?.contentWindow?.postMessage(message, '*');
    }
  }
</script>

<style>
  .btd-permission-dialog {
    iframe {
      width: 100%;
      height: calc(100vh - 65px);
    }
  }
  .init-role-data-rule-drawer {
    display: none;
  }
</style>
